<?php
/**
 * 商户管理
 * User: hls
 * Date: 2016/3/21
 * Time: 10:10
 */

namespace Admin\Controller;
use Admin\BaseController;
use Admin\Model\AddressModel;
use Common\Model\CouponModel;
use Common\Model\BusinessModel;
use Common\Model\UtilsModel;
use Think\Db;
use Think\Page;

class BusinessController extends BaseController
{
    /**
     * restaurantList 商家列表
     */
    public function restaurantList(){
        $keyword=I('get.keyword',null);


        $restaurant = M('s_restaurant',null,DB_MAIN_CFG);
        $store = M('s_store',null,DB_MAIN_CFG);
        $card_info = M('card_base_info',null,DB_MAIN_CFG);
        $verification = M('s_verification',null,DB_MAIN_CFG);
        $consume_log = M('card_code',null,DB_MAIN_CFG);


        $where='1';
        if($keyword){
            $where .=" and restaurantName like '%{$keyword}%'";
        }


        //分页
        $count = $restaurant->where($where)->count();
        $this->smarty->assign('totalDataCount',$count);

        $limit = I('get.limit',10,'int');	//每页显示条数
        $Page = new Page($count, $limit);
        //分页
        fetchPage($this->smarty, $Page);
        //分页输出
        //商家列表
        $list = $restaurant
            ->where($where)
            ->order('id desc')
            ->limit($Page->firstRow,$Page->listRows)
            ->select();
        //查出该商家下有多少门店
        $store_num_list = $store->field('count(*) as storeNum,restaurantId as id')->group('restaurantId')->order('restaurantId desc')->select();
        //查出该商家下有多少核销员
        $verification_num_list = $verification->field('count(*) as verificationNum,restaurantId as id')->group('restaurantId')->order('restaurantId desc')->select();
        //查出该商家下有多少卡券
        $card_info_num_list = $card_info->field('count(*) as cardinfoNum,restaurantId as id,0 as launchNum')->group('restaurantId')->order('restaurantId desc')->select();
        //查出该商家下有多少卡券被核销
        $card_list_consume_num = $consume_log->Field('count(*) as consume_num,restaurantId as id')->group('restaurantId')->order('restaurantId desc')->select();

        //合并list
        foreach($list as $key => $value){
            $list[$key]['storeNum'] = 0;
            $list[$key]['verificationNum'] = 0;
            $list[$key]['cardinfoNum'] = 0;
            $list[$key]['launchNum'] = 0;
            $list[$key]['consume_num'] = 0;
            //合并门店数量
            foreach($store_num_list as $k => $v){
                if($v['id'] == $value['id']){
                    $list[$key]['storeNum'] += $v['storeNum'];
                    unset($store_num_list[$k]);
                }
            }
            //合并核销员数量
            foreach($verification_num_list as $k => $v){
                if($v['id'] == $value['id']){
                    $list[$key]['verificationNum'] += $v['verificationNum'];
                    unset($verification_num_list[$k]);
                }
            }
            //合并卡券数量
            foreach($card_info_num_list as $k => $v){
                if($v['id'] == $value['id']){
                    $list[$key]['cardinfoNum'] += $v['cardinfoNum'];
                    unset($card_info_num_list[$k]);
                }
            }
            //合并发放的卡券数量
            foreach($card_list_consume_num as $k => $v){
                if($v['id'] == $value['id']){
                    $list[$key]['consume_num'] += $v['consume_num'];
                    unset($card_list_consume_num[$k]);
                }
            }
            //计算核销率
            if($list[$key]['launchNum'] == 0 || $list[$key]['consume_num'] == 0){
                $list[$key]['consume_percent'] = 0;
            }else{
                $list[$key]['consume_percent'] =  ($list[$key]['consume_num']/$list[$key]['launchNum'])*100;
            }
        }
        $this->smarty->assign('list', $list);
        $this->smarty->assign('keyword', $keyword);
        $this->smarty->assign('limit',$limit);
        $this->smarty->display('Business/restaurant_list.html');
    }
    
    /**
     * restaurantAdd 商家添加
     */
    public function restaurantAdd(){
        if(IS_POST){
            $photo          =I('post.photo');
            $restaurantName =I('post.restaurantName');
            if(!$photo){
                $this->error('请选择商户图片');
            }
            if(!$restaurantName){
                $this->error('商户名称是必须的');
            }

            $director       =I('post.director');
            $phone          =I('post.phone');
            //判断手机的格式是否正确
            if($phone && !(filedPreMatch('phone', $phone))) {
                $this->error('手机格式不正确');
            }
            if(BusinessModel::checkPhoneExist($phone)){
                $this->error('该手机码已经存在');
            }

            $password       =I('post.password');


            $newData=array(
                'photo'=>$photo,
                'restaurantName'=>$restaurantName,
                'phone'=>$phone,
                'director'=>$director,
                'updateTime'=>time(),
                'status'=>1
            );
            $restaurant = M('s_restaurant',null,DB_MAIN_CFG);
            $resID = $restaurant->add($newData);
            if($resID === false){
                    $this->error($restaurant->getError());
            }

            //创建商户管理员
            if($phone && $director && $password) {
                /**
                 * 添加|修改核销员
                 * @param $data {id,phone,password,verificationName,role_id,restaurantId,storeId,jobNum,adminId}
                 * @return bool
                 */
                $data=array(
                    'phone'             => $phone,
                    'password'          => $password,
                    'verificationName'  => $director,
                    'role_id'           => ROLE_RESTAURANT_ID,
                    'restaurantId'      => $resID,
                    'storeId'           => 0,
                    'jobNum'            => '001',
                    'adminId'           => 0
                );
                BusinessModel::verificationEdit($data);
            }
            $this->success('添加成功');

        }else{
            $this->smarty->display('Business/restaurant_add.html');
        }
    }

    /**
     * restaurantEdit 商家编辑
     */
    public function restaurantEdit(){
        //获取id
        $id = I('get.id',null);
        //如果没有id 则无法进行编辑
        if(empty($id)){
           $this->error('非法操作');
        }
        $restaurant = M('s_restaurant',null,DB_MAIN_CFG);
        if(IS_POST){

            $photo          =I('post.photo');
            $restaurantName =I('post.restaurantName');
            if(!$photo){
                $this->error('请选择商户图片');
            }
            if(!$restaurantName){
                $this->error('商户名称是必须的');
            }

            $director       =I('post.director');

            $phone          =I('post.phone');
            //判断手机的格式是否正确
            if($phone && !(filedPreMatch('phone', $phone))) {
                $this->error('手机格式不正确');
            }
            if(BusinessModel::checkPhoneExist($phone,$id)){
                $this->error('该手机码已经存在');
            }


            $password       =I('post.password');

            $newData=array(
                'photo'=>$photo,
                'restaurantName'=>$restaurantName,
                'phone'=>$phone,
                'director'=>$director,
                'updateTime'=>time(),
                'status'=>1
            );
            $restaurant = M('s_restaurant',null,DB_MAIN_CFG);
            $resID = $restaurant->where('id='.$id)->save($newData);
            if($resID === false){
                $this->error($restaurant->getError());
            }

                //创建商户管理员
                /**
                 * 添加|修改核销员
                 * @param $data {id,phone,password,verificationName,role_id,restaurantId,storeId,jobNum,adminId}
                 * @return bool
                 */
                $data=array(
                    'id'                =>I('post.verificationId'),
                    'phone'             => $phone,
                    'password'          => $password,
                    'verificationName'  => $director,
                    'role_id'           => ROLE_RESTAURANT_ID,
                    'restaurantId'      => $id,
                    'storeId'           => 0,
                    'jobNum'            => '001',
                    'adminId'           => I('post.adminId')
                );
                $result=BusinessModel::verificationEdit($data);
                if ($result === false) {
                    $this->error($restaurant->getError());
                }
            $this->success('修改成功');
        }
        else{
            //输出显示
            $item = $restaurant->find($id);
            if(empty($item)){
                $this->error('不存在该商家');
            }
            $this->smarty->assign('item', $item);

            $this->smarty->assign('picWidth',C("ARTICLE_PIC_WIDTH"));
            $this->smarty->assign('picHeight',C("ARTICLE_PIC_HEIGHT"));

            $verification=BusinessModel::getVerificationByBelong($id,ROLE_RESTAURANT_ID);
            $this->smarty->assign('verificationId', $verification['id']);
            $this->smarty->assign('adminId', $verification['adminId']);

            $this->smarty->display('Business/restaurant_edit.html');
        }
    }

    /**
     * restaurantDelete 商家更改启用状态
     */
    public function restaurantUpdate(){
        $id = I('get.id', null, 'intval');
        $restaurant = M('s_restaurant',null,DB_MAIN_CFG);
        $item = $restaurant->find($id);
        if(empty($item)){
            $this->error('没有存在该商户');
        }
        if($item['status']) {
            $result = $restaurant->where('id=' . $id)->setField('status', 0);
        }else{
            $result = $restaurant->where('id=' . $id)->setField('status', 1);
        }
        if ($result) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * storeList 门店列表
     */
    public function storeList(){
        $restaurantId = I('get.id',0,'int');
        $keyword=I('get.keyword');

        $store = M('s_store',null,DB_MAIN_CFG);
        $card_info = M('card_base_info',null,DB_MAIN_CFG);
        $verification = M('s_verification',null,DB_MAIN_CFG);
        $consume_log = M('card_code',null,DB_MAIN_CFG);

        $where='1';
        if($restaurantId!=0){
            $where .=' and restaurantId = '.$restaurantId;
        }
        if($keyword){
            $where .=" and storeName like '%{$keyword}%'";
        }


        $count = $store->where($where)->count();
        $this->smarty->assign('totalDataCount',$count);


        $limit = I('get.limit',10,'int');	//每页显示条数
        $Page = new Page($count,$limit);
        //分页
        fetchPage($this->smarty, $Page);

        $list =$store->field('s_restaurant.restaurantName,s_store.restaurantId,s_store.storeName,s_store.id,s_store.address,s_store.status,s_store.commentNum')
            ->join('left join s_restaurant on s_restaurant.id = s_store.restaurantId')
            ->where($where)
            ->order('s_store.updateTime desc')
            ->limit($Page->firstRow , $Page->listRows)
            ->select();


        //查出该门店下有多少核销员
        $verification_num_list = $verification->field('count(*) as verificationNum,storeId as id')->group('storeId')->order('storeId desc')->select();
        //查出该门店下有多少卡券
        $card_info_num_list = $card_info->field('storeId as id,sum(launchNum) as launchNum')->group('storeId')->select();
        //查出该门店下有多少卡券被核销
        $card_list_consume_num = $consume_log->Field('count(*) as consume_num,storeId as id')->group('storeId')->order('storeId desc')->select();
        //合并list
        foreach($list as $key => $value){
            //初始化卡券种类为0 发行数量为0
            $list[$key]['cardinfoNum'] = 0;
            $list[$key]['launchNum'] = 0;
            $list[$key]['verificationNum'] = 0;
            $list[$key]['consume_num'] = 0;
            //合并发行数量
            foreach($card_info_num_list as $k => $v){
                if(stripos(','.$v['id'].',',','.$value['id'].',')!==FALSE){
                    $list[$key]['launchNum'] += intval($v['launchNum']);
                    $list[$key]['cardinfoNum']++;
                }
            }
            //合并核销员数量
            foreach($verification_num_list as $k => $v){
                if($v['id'] == $value['id']){
                    $list[$key]['verificationNum'] += $v['verificationNum'];
                    unset($verification_num_list[$k]);
                }
            }
            //合并发放的卡券数量
            foreach($card_list_consume_num as $k => $v){
                if($v['id'] == $value['id']){
                    $list[$key]['consume_num'] += $v['consume_num'];
                    unset($card_list_consume_num[$k]);
                }
            }
            //计算核销率
            if($list[$key]['launchNum'] == 0 || $list[$key]['consume_num'] == 0){
                $list[$key]['consume_percent'] = 0;
            }else{
                $list[$key]['consume_percent'] =  round(($list[$key]['consume_num']/$list[$key]['launchNum'])*100,2);
            }
        }

        $this->smarty->assign('list', $list);

        $restaurant=BusinessModel::getRestaurantKV();

        $this->smarty->assign('restaurantKv', $restaurant);
        $this->smarty->assign('keyword', $keyword);
        $this->smarty->assign('limit',$limit);
        $this->smarty->assign('id', $restaurantId);

        $this->smarty->display('Business/store_list.html');
        die('ok');
    }
    /**
     * storeAdd 门店增加
     */
    public function storeAdd(){
        $restaurant = M('s_restaurant',null,DB_MAIN_CFG);
        if(IS_POST){
            $restaurantId = I('post.restaurantId',0);

            $phone=I('post.phone');
            $password=I('post.password');
            //判断手机的格式是否正确
            if($phone && !(filedPreMatch('phone', $phone))) {
                $this->error('手机格式不正确');
            }

            $newVerification=false;
            //如存在同手机号的商户管理，则跳过核销员添加
            if(!M('s_verification',null,DB_MAIN_CFG)->where("restaurantId={$restaurantId} and phone='{$phone}' and role_id=".ROLE_RESTAURANT_ID)->find()){
                if(BusinessModel::checkPhoneExist($phone)){
                    $this->error("该手机号已存在");
                }
                $newVerification=true;
            }

            $restaurantItem = $restaurant->find($restaurantId);
            if(empty($restaurantItem)){
                $this->error('商家不存在');
            }


            $store = M('s_store',null,DB_MAIN_CFG);
            $rules = array(
                array('storeName', 'require', '门店名称必须填写'),
                array('address', 'require', '门店地址必须填写'),
                array('restaurantId', 'require','所属的商家必须填写'),
            );
            $auto = array(
                array('updateTime', 'time', 3, 'function'),
            );


            if($data = $store->validate($rules)->auto($auto)->create()){
                 $data['album']=implode(',',I('post.album'));
                 $data['businessItem']=implode(',',I('post.businessItem'));
                 $storeId=$store->add($data);
                if($newVerification) {
                    //创建门店管理员
                    /**
                     * 添加|修改核销员
                     * @param $data {id,phone,password,verificationName,role_id,restaurantId,storeId,jobNum,adminId}
                     * @return bool
                     */
                    $data = array(
                        //'id'                =>I('post.verificationId'),
                        'phone' => $data['phone'],
                        'password' => $password,
                        'verificationName' => $data['director'],
                        'role_id' => ROLE_STORE_ID,
                        'restaurantId' => $data['restaurantId'],
                        'storeId' => $storeId,
                        'jobNum' => '002',
                        'adminId' => 0
                    );
                    $result = BusinessModel::verificationEdit($data);
                    if ($result === false) {
                        $this->error($restaurant->getError());
                    }
                }
                 $this->success('添加成功');
            }else{
                $this->error($store->getError());
            }
        }
        else{
            $restaurantId = I('get.id',0);
            $restaurantItem = $restaurant->find($restaurantId);
            if(empty($restaurantItem)){
                $restaurantList = BusinessModel::getRestaurantKv();
                $this->smarty->assign('restaurantList',$restaurantList);
                $this->smarty->assign('restaurantId', 0);
            }else{
                $this->smarty->assign('restaurantName',$restaurantItem['restaurantName']);
                $this->smarty->assign('restaurantId', $restaurantItem['id']);
            }

            $provinceKV = include_once(WEB_ROOT.'/data/area_info/area_province_list.php');
            $this->smarty->assign('province',$provinceKV);

            $restaurant=M('s_restaurant',null,DB_MAIN_CFG)->field('id,restaurantName')->select();
            $this->smarty->assign('restaurant', $restaurant);

            $businessItemKv=BusinessModel::getBusinessItemKv();
            $this->smarty->assign('businessItemKv',$businessItemKv);

            $jobNum=BusinessModel::createRandomJobNumber($restaurantId);
            $this->smarty->assign('jobNum',$jobNum);

            $this->smarty->display('Business/store_edit.html');
        }
    }
    /**
     * storeEdit 门店编辑
     */
    public function storeEdit(){
        $storeId = I('get.id',null,'intval');
        $storeM = M('s_store',null,DB_MAIN_CFG);
        $storeInfo = $storeM->find($storeId);
        $restaurant = M('s_restaurant',null,DB_MAIN_CFG);
        if(empty($storeInfo)){
            $this->error('不存在该门店');
        }
        if(IS_POST){
            $verificationId = I('post.verificationId',0,'intval');
            $adminId        = I('post.adminId',0,'intval');

            $phone=I('post.phone');
            $password=I('post.password');
            //判断手机的格式是否正确
            if($phone && !(filedPreMatch('phone', $phone))) {
                $this->error('手机格式不正确');
            }

            $restaurantId=I('post.restaurantId',0,'intval');
            $newVerification=false;
            //如存在同手机号的商户管理，则跳过核销员添加
            $sameWithRestaurant=M('s_verification',null,DB_MAIN_CFG)->where("restaurantId={$restaurantId} and phone='{$phone}' and role_id=".ROLE_RESTAURANT_ID)->find();
            if(!$sameWithRestaurant){
                if(BusinessModel::checkPhoneExist($phone,$verificationId)){
                    $this->error("该手机号已存在");
                }
                $newVerification=true;
            }

            $restaurantItem = $restaurant->find($restaurantId);
            if(empty($restaurantItem)){
                $this->error('商家不存在');
            }
            
            $rules = array(
                array('id', 'require', 'id必须填写'),
                array('storeName', 'require', '门店必须填写'),
                array('address', 'require', '门店地址必须填写'),
                array('restaurantId', 'require','所属的商户必须填写'),
            );
            $auto = array(
                array('updateTime', 'time', 3, 'function'),
            );

            if($data = $storeM->validate($rules)->auto($auto)->create()){
                $data['album']=implode(',',I('post.album'));
                $data['businessItem']=implode(',',I('post.businessItem'));
                $result = $storeM->save($data);

                if($newVerification) {
                    //创建门店管理员
                    $data = array(
                        'id'        =>$verificationId,
                        'phone'     => $data['phone'],
                        'password'  => $password,
                        'verificationName'  => $data['director'],
                        'role_id'           => ROLE_STORE_ID,
                        'restaurantId'      => $data['restaurantId'],
                        'storeId'   => $data['id'],
                        'jobNum'    => '002',
                        'adminId'   => $adminId
                    );
                    $result = BusinessModel::verificationEdit($data);
                    if ($result === false) {
                        $this->error($restaurant->getError());
                    }
                }else{
                    //使用商户管理员，原核销员删除 
                    BusinessModel::verificationDel($verificationId);
                }

                $this->success('修改成功');
            }
            else{
                $this->error($storeM->getError());
            }
        }
        else{
            $provinceKV = include_once(WEB_ROOT.'/data/area_info/area_province_list.php');
            $this->smarty->assign('province',$provinceKV);
            if($storeInfo['province']){
                $province = include_once(WEB_ROOT.'/data/area_info/'.$storeInfo['province'].'.php');
                $storeInfo['provinceName'] = $province[$storeInfo['province']]['name'];
                $addStr = $storeInfo['provinceName'];
                if($storeInfo['city']) {
                    $storeInfo['cityName'] = $province[$storeInfo['city']]['name'];
                    $addStr .= "/".$storeInfo['cityName'];
                }
                if($storeInfo['district']) {
                    $storeInfo['districtName'] = $province[$storeInfo['district']]['name'];
                    $addStr .= "/".$storeInfo['districtName'];
                }
                $this->smarty->assign('address',$addStr);
            }

            $this->smarty->assign('obj', $storeInfo);

            $album=explode(',',$storeInfo['album']);
            $this->smarty->assign('album', $album);

            $restaurant=M('s_restaurant',null,DB_MAIN_CFG)->field('id,restaurantName')->select();
            $this->smarty->assign('restaurant', $restaurant);

            $tradeAreaKV=UtilsModel::getTradeAreaKV($storeInfo['district']);
            $this->smarty->assign('tradeArea', $tradeAreaKV);


            $businessItemKv=BusinessModel::getBusinessItemKv();
            $this->smarty->assign('businessItemKv',$businessItemKv);

            $selectedItems=explode(',',$storeInfo['businessItem']);
            $this->smarty->assign('selectedItems',$selectedItems);

            $verification=BusinessModel::getVerificationByBelong($storeId,ROLE_STORE_ID);

            $this->smarty->assign('verificationId', $verification['id']);
            $this->smarty->assign('adminId', $verification['adminId']);
            if(!$verification['jobNum']){
                $verification['jobNum']=BusinessModel::createRandomJobNumber($storeInfo['restaurantId']);
            }
            $this->smarty->assign('jobNum', $verification['jobNum']);



            $this->smarty->display('Business/store_edit.html');
        }
    }
    /**
     * storeUpdate 门店更改启用状态
     */
    public function storeUpdate(){
        $id = I('get.id', null, 'intval');
        $store = M('s_store',null,DB_MAIN_CFG);
        $item = $store->find($id);
        if(empty($item)){
            $this->error('没有存在该门店');
        }
        if($item['status']) {
            $result = $store->where('id=' . $id)->setField('status', ENABLE_DISABLE);
        }else{
            $result = $store->where('id=' . $id)->setField('status', ENABLE_ENABLE);
        }
        if ($result) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }


    public function getArea_info(){
        $area_id = I('post.area_id',0,'int');
        $level = I('post.level',0,'int');
        $provinceID = I('post.provinceID',0,'int');
        
        $areaArr = AddressModel::getArea_info($area_id,$level,$provinceID);
        $this->smarty->assign('add',$areaArr);
        $html = $this->smarty->fetch("Business/address.html");
        $return['dataHtml'] = $html;
        $this->ajaxReturn($return);
    }

    public function getTradeAreaKV(){
        $areaId= I('post.areaId',0,'int');
        $data=UtilsModel::getTradeAreaKV($areaId);
        $this->smarty->assign('add',$data);
        $html = $this->smarty->fetch("Business/tradeArea.html");
        $return['dataHtml'] = $html;
        $this->ajaxReturn($return);
    }


    /**
     * verficationList 核销员列表
     */
    public function verificationList(){
        $name   = I('get.name',null);
        $phone  = I('get.phone');

        $where="1";
        if($name){
            $where .=" and s_verification.verificationName like '%{$name}%'";
        }
        if($phone){
            $where .=" and s_verification.phone like '%{$phone}%'";
        }

        $verification = M('s_verification',null,DB_MAIN_CFG);
        //分页
        $count = $verification->where($where)->count();
        $this->smarty->assign('totalDataCount',$count);

        $limit = I('get.limit',10,'int');	//每页显示条数
        $Page = new Page($count,$limit);
        //分页
        fetchPage($this->smarty, $Page);
        //因为要输出商户名字和门店名字  3表联合查询
        $list = $verification
            ->field('s_verification.id,s_verification.verificationName,s_verification.verifyNum,
            s_verification.jobNum,s_verification.phone,s_verification.status,
            s_store.storeName,s_restaurant.restaurantName')
            ->join('left join s_store on s_verification.storeId = s_store.id')
            ->join('left join s_restaurant on s_restaurant.id = s_verification.restaurantId')
            ->limit($Page->firstRow,$Page->listRows)
            ->where($where)
            ->select();
        $this->smarty->assign('list', $list);
        $this->smarty->assign('limit', $limit);
        $this->smarty->assign('name', $name);
        $this->smarty->assign('phone', $phone);

        $restaurantKV=BusinessModel::getRestaurantKV();
        $this->smarty->assign('restaurantKV', $restaurantKV);

        $this->smarty->display('Business/verification_list.html');
    }

    /**
     * verificationAdd 核销员添加
     */
    public function verificationAdd(){
        if(IS_AJAX){
            $phone=I('post.phone','');
            if(BusinessModel::checkPhoneExist($phone)){
                $this->ajaxReturn(array('status'=>1,'msg'=>'该手机码已经存在'));
            }
            $this->ajaxReturn(array('status'=>0));
        }
        elseif(IS_POST) {
            $verification = M('s_verification',null,DB_MAIN_CFG);
            $sysUser = M("sp_sys_user",null,DB_GM_CFG);
            $rule = array(
                array('verificationName','require','核销员必须填写'),
                array('phone','require','手机必须填写'),
                array('restaurantId','require','所属商会id必须填写'),
                array('storeId','require','所属门店id必须填写'),
            );
            $auto = array(
                array('updateTime', 'time', 3, 'function'),
            );
            //判断手机的格式是否正确
            if(!(filedPreMatch('phone', $_POST['phone']))) {
                $this->error('手机格式不正确');
            }

            if(BusinessModel::checkPhoneExist($_POST['phone'])){
                $this->error('该手机码已经存在');
            }

            if($data = $verification->validate($rule)->auto($auto)->create()){

                //判断用户有没有输入工号 没有输入工号 则自动生成
                if($data['jobNum'] != ''){
                    //判断核销员的工号格式是否正确
                    if(!(filedPreMatch('jobNum', $data['jonNumber']))) {
                        $this->error('工号格式不正确，工号为3位');
                    }
                    //判断该工号在该商家内 是不是唯一
                    $verificationItem = $verification->where('id=' . $data['restaurantId'] . ' and jobNum=' . $data['jobNum'])->select();
                    if($verificationItem){
                        $this->error('该工号已存在，请重新输入');
                    }
                }else{
                    $data['jobNum'] = BusinessModel::createRandomJobNumber($data['restaurantId']);
                    if($data['jobNum'] ===false){
                        $this->error("已经没有多余工号可以分配");
                    }
                }
                //在添加核销员的同时 再给该核销员 生成登录账号
                $sysUseData = array(
                     'username' => $data['phone'],
                     'password' => md5(I('post.password')),
                     'real_name'=> $data['verificationName'],
                     'phone'    => $data['phone'],
                     'belong'   => $data['storeId'],
                     'role_id'  => ROLE_TELLER_ID
                );

                //添加用户的时候 是否添成功
                $result = $sysUser->add($sysUseData);
                //添加成功后 绑定uid
                $data['uid'] = $result;
                //添加核销员
                $verification->add($data);
                $this->success('添加成功');
            }else{
                $this->error($verification->getError());
            }
        }
        else {
            //id 为门店id
            $id = I('get.id', null);
            //rid 为商会id
            $rid = I('get.rid', null);
            $store = M('s_store', null, DB_MAIN_CFG);
            $restaurant = M('s_restaurant', null, DB_MAIN_CFG);
            $storeItem = $store->field('id,storeName')->find($id);
            $restaurantItem = $restaurant->field('id,restaurantName')->find($rid);
            $jobNum = BusinessModel::createRandomJobNumber($rid);
            if (empty($storeItem)) {
                $this->error('不存该门店');
            }
            if (empty($restaurantItem)) {
                $this->error('不存该商户');
            }
            $this->smarty->assign('jobNum',$jobNum);
            $this->smarty->assign('storeItem', $storeItem);
            $this->smarty->assign('restaurantItem', $restaurantItem);
            $this->smarty->display('Business/verification_edit.html');
        }
    }

    /**
     * verficationEdit 核销员编辑
     */
    public function verificationEdit(){
        $verification = M('s_verification',null,DB_MAIN_CFG);
        if(IS_AJAX){
            $phone=I('post.phone','');
            $id=I('post.id','');
            if(BusinessModel::checkPhoneExist($phone,$id)){
                $this->ajaxReturn(array('status'=>1,'msg'=>'该手机码已经存在'));
            }
            $this->ajaxReturn(array('status'=>0));
        }
        elseif(IS_POST) {
            $rule = array(
                array('id','require','请指定核销员'),
                array('verificationName','require','核销员必须填写'),
                array('phone','require','手机必须填写'),
            );
            $auto = array(
                array('updateTime', 'time', 3, 'function'),
            );
            //判断手机的格式是否正确
            if(!(filedPreMatch('phone', $_POST['phone']))) {
                $this->error('手机格式不正确');
            }
            if(BusinessModel::checkPhoneExist($_POST['phone'],$_POST['id'])){
                $this->error('该手机码已经存在');
            }
            if($data = $verification->validate($rule)->auto($auto)->create()){
                $result = $verification->save($data);
                if($result !== FASLE){
                    $this->success('修改成功');
                }else{
                    $this->error('修改失败');
                }
            }else{
                $this->error($verification->getError());
            }
        }
        else{
            $id = I('get.id',null,'intval');
            $store = M('s_store', null, DB_MAIN_CFG);
            $restaurant = M('s_restaurant', null, DB_MAIN_CFG);
            $item = $verification->find($id);
            if(empty($item)){
                $this->error('不存在该核销员');
            }
            $storeItem = $store->field('id,storeName')->find($item['storeId']);
            $restaurantItem = $restaurant->field('id,restaurantName')->find($item['restaurantId']);
            $this->smarty->assign('storeItem', $storeItem);
            $this->smarty->assign('restaurantItem', $restaurantItem);

            $this->smarty->assign('item',$item);
            $this->smarty->display('Business/verification_edit.html');
        }
    }
    /**
     * verificateionUpdate 核销员修改状态 1为启用 0为不启用
     */
    public function verificationUpdate(){
        $id = I('get.id', null, 'intval');
        $verification = M('s_verification',null,DB_MAIN_CFG);
        $item = $verification->find($id);
        if(empty($item)){
            $this->error('没有存在该核销员');
        }
        if($item['status']) {
            $result = $verification->where('id=' . $id)->setField('status', 0);
        }else{
            $result = $verification->where('id=' . $id)->setField('status', 1);
        }
        if ($result) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }
    /**
     * verificateionLog 核销员核销记录
     */
    public function verificationLog(){
        $id = I('get.id',null);
        $verification = M('s_verification',null,DB_MAIN_CFG);
        $consume_log = M("card_code",null,DB_MAIN_CFG);
        $store = M('s_store',null,DB_MAIN_CFG);
        $verificationItem = $verification->find($id);
        if(empty($verificationItem)){
            $this->error('不存在该核销员');
        }


        $storeName = $store->field('storeName')->where('id='.$verificationItem['storeId'])->find();
        $consume_log_list = $consume_log->where("verificationId='{$id}'")->select();

        foreach ($consume_log_list as $key => $value) {
            $consume_log_list[$key] = array_merge($value,$storeName);
        }
        $this->smarty->assign('name',$verificationItem['verificationName']);
        $this->smarty->assign('list',$consume_log_list);
        $this->smarty->display('Business/verificateion_log.html');
    }

    
    public function storePackage(){
        $restaurantId   = I('get.restaurantId',0,'int');
        $storeId        = I('get.storeId',0,'int');
        $page           = I('get.page',1,'int');
        $pageSize       = I('get.limit',10,'int');

        $data=BusinessModel::getPackageList($page,$pageSize,$restaurantId,$storeId);
        $this->smarty->assign('prevPage',$data['page'] >1 ? $data['page']-1:0);
        $this->smarty->assign('nextPage',$data['page'] <$data['totalPage'] ? $data['page']+1:0);
        $this->smarty->assign('nowPage',$data['page']);
        $this->smarty->assign('totalPage',$data['totalPage']);

        $this->smarty->assign('totalDataCount',$data['total']);


        $this->smarty->assign('list', $data['data']);

        $restaurantKV=BusinessModel::getRestaurantKV();
        $this->smarty->assign('restaurantKV', $restaurantKV);

        $storeKV=BusinessModel::getStoreKV(BusinessModel::PARTNER_TYPE_YES);
        $this->smarty->assign('storeKV', $storeKV);

        $this->smarty->assign('limit',$pageSize);
        $this->smarty->assign('restaurantId', $restaurantId);
        $this->smarty->assign('storeId', $storeId);

        $this->smarty->display('Business/package_list.html');
    }
    public function storePackageAdd(){
        $restaurant = BusinessModel::getInstance();
        if(IS_POST){
            $restaurantId = I('post.restaurantId',0,'intval');
            $restaurantItem = $restaurant->find($restaurantId);
            if(!$restaurantItem){
                $this->error('指定商家不存在');
            }

            $store = BusinessModel::getStoreInstance();
            $storeId = I('post.restaurantId',0,'intval');
            if(!$store->find($storeId)){
                $this->error('指定门店不存在');
            }

            $rules = array(
                array('title', 'require', '套餐名称必须填写'),
                array('pricePresent', 'require', '优惠价必须填写'),
                array('priceOriginal', 'require','原价必须填写'),
            );
            $auto = array(
                array('addTime', 'time', 3, 'function'),
            );

            $packageM=BusinessModel::getPackageInstance();
            if($data = $packageM->validate($rules)->auto($auto)->create()){
                $data['album']=implode(',',I('post.album'));
                $packageM->add($data);
                $this->success('添加成功');
            }else{
                $this->error($store->getError());
            }
        }else{
            $id = I('get.id',0);
            $restaurantItem = $restaurant->find($id);
            if(empty($restaurantItem)){
                $restaurantList = BusinessModel::getRestaurantKv();
                $this->smarty->assign('restaurantList',$restaurantList);
                $this->smarty->assign('restaurantId', 0);
            }else{
                $this->smarty->assign('restaurantName',$restaurantItem['restaurantName']);
                $this->smarty->assign('restaurantId', $restaurantItem['id']);
            }


            $restaurant=M('s_restaurant',null,DB_MAIN_CFG)->field('id,restaurantName')->select();
            $this->smarty->assign('restaurant', $restaurant);

            $this->smarty->display('Business/package_edit.html');
        }
    }
    public function storePackageEdit(){
        $restaurant = BusinessModel::getInstance();
        if(IS_POST) {
            $restaurantId = I('post.restaurantId',0,'intval');
            $restaurantItem = $restaurant->find($restaurantId);
            if(!$restaurantItem){
                $this->error('指定商家不存在');
            }

            $store = BusinessModel::getStoreInstance();
            $storeId = I('post.storeId',0,'intval');
            if(!$store->find($storeId)){
                $this->error('指定门店不存在');
            }

            $rules = array(
                array('title', 'require', '套餐名称必须填写'),
                array('pricePresent', 'require', '优惠价必须填写'),
                array('priceOriginal', 'require','原价必须填写'),
            );


            $packageM=BusinessModel::getPackageInstance();
            if($data = $packageM->validate($rules)->create()){
                $data['album']=implode(',',I('post.album'));
                $result=$packageM->save($data);
                if($result !== FASLE){
                    $this->success('修改成功');
                }else{
                    $this->error('修改失败');
                }
            }else{
                $this->error($store->getError());
            }
        }
        else {

            $id = I('get.id',null,'intval');
            $packageM = BusinessModel::getPackageInstance();
            $item = $packageM->find($id);

            $this->smarty->assign('obj', $item);

            $storeName=BusinessModel::getStoreInstance()->where("id={$item['storeId']}")->getfield('storeName');
            $this->smarty->assign('storeName', $storeName);



            $album=explode(',',$item['album']);
            $this->smarty->assign('album', $album);

            $restaurant=M('s_restaurant',null,DB_MAIN_CFG)->field('id,restaurantName')->select();
            $this->smarty->assign('restaurant', $restaurant);

            $this->smarty->display('Business/package_edit.html');
        }
    }
    public function storePackageDel(){
        $id = I('get.id',0,'intval');
        if(!$id){
            $this->error('请指定套餐');
        }
        BusinessModel::getPackageInstance()->where("id={$id}")->delete();
        $this->success('删除成功');
    }


    public function storePackageAudit(){
        $id = I('get.id',0,'intval');
        if(!$id){
            $this->error('请指定套餐');
        }
        $status = I('get.status',0,'intval');
        if($status!=ENABLE_ENABLE){
            $status=ENABLE_DISABLE;
        }
        BusinessModel::getPackageInstance()->where("id={$id}")->setField('status',$status);
        $this->success('操作成功');
    }


    /*
     * 月统计
     */
    public function monthRecord(){
        //获取商户
        $restaurantM = M('s_restaurant',null,DB_MAIN_CFG);
        $restaurant = $restaurantM->where("status = 1")->getField("id,restaurantName",true);
        $this->smarty->assign("restaurant",$restaurant);

        //获取门店
        $storeM = M('s_store',null,DB_MAIN_CFG);
        $store = $storeM->where("status = 1")->getField("id,storeName",true);
        $this->smarty->assign('store',$store);
        if($_GET){
            $where = "1";
            $startDate = I('get.startDate',null);
            $endDate = I('get.endDate',null);

            if($startDate){
                $begin=strtotime($startDate);
                $beginTime = mktime(0,0,0,date("m",$begin),date("d",$begin),date("Y",$begin));
                $where .=" and addTime >= $beginTime";
            }

            if($endDate){
                $end=strtotime($endDate);
                $endTime = mktime(23,59,59,date("m",$end),date('t',$end),date("Y",$end));
                $where .=" and addTime <= $endTime";
            }

            $selectedRestaurant = I('get.restaurant',-1,'int');
            if($selectedRestaurant >= 0 ){
                $where .=" and restaurantId = {$selectedRestaurant}";
            }

            $selectedStore = I('get.store',0,'int');
            if($selectedStore > 0 ){
                $where .=" and verificationStoreId = {$selectedStore}";
            }
            $export = I('get.export',0,'int');
            $cardConsumeM = M('statistic_card_consume_monthly',null,DB_MAIN_CFG);

            $count = $cardConsumeM->where($where)->count();
            $limit = I('get.limit',10,'int');	//每页显示条数
            $Page = new Page($count,$limit);
            fetchPage($this->smarty, $Page);
            //卡券类型
            $card_type = CouponModel::getCardType();
            if($export){
                $list = $cardConsumeM->where($where)->order("addTime DESC,restaurantId ASC,verificationStoreId ASC,cardId ASC")->select();
                $data = array();
                foreach ($list as $key => $val){
                    $data[$key]['consumeTime'] = date('Y-m',$val['addTime']);
                    $data[$key]['restaurantName'] = $val['restaurantName'];
                    $data[$key]['storeName'] = $val['storeName'];
                    $data[$key]['cardTitle'] = $val['cardTitle'];
                    $data[$key]['cardType'] = $card_type[$val['cardType']];
                    $data[$key]['consumeNum'] = $val['consumeNum'];
                }
                exportExcel($data, array('核销时间','商户名称','门店名称','卡券名','卡券类型','核销数量'),'卡券核销月统计');
                exit;
            } else{
                $list = $cardConsumeM->where($where)->limit($Page->firstRow.','.$Page->listRows)->order("addTime DESC,restaurantId ASC,verificationStoreId ASC,cardId ASC")->select();

                $this->smarty->assign('startDate',$startDate);
                $this->smarty->assign('endDate',$endDate);
                $this->smarty->assign('selectedRestaurant',$selectedRestaurant);
                $this->smarty->assign('selectedStore',$selectedStore);
                $this->smarty->assign('cardType',$card_type);
                $this->smarty->assign('limit',$limit);

                $this->smarty->assign('list',$list);
                $this->smarty->display('Business/month_record.html');
            }
        }
    }
}
